package com.dao.impl;

import com.dao.BannerService;
import com.entity.Banner;
import com.util.JdbcUtil;
import com.util.PageUtil;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author lzy
 * @since 2022-03-24
 */
public class BannerServiceImpl implements BannerService {

	@Override
	public int insert(Banner banner) throws SQLException {
		String sql = "insert banner (image_url,to_router_url,to_url,sort,create_time,update_time,is_deleted) values (?,?,?,?,?,?,0)";
		List<Object> ans = new ArrayList<>();

		if(banner == null) {
			return  0;
		}

		ans.add(banner.getImageUrl());
		ans.add(banner.getToRouterUrl());
		ans.add(banner.getToUrl());
		ans.add(banner.getSort());
		ans.add(new Date());
		ans.add(new Date());

		return JdbcUtil.insertOrUpdateOrDelete(sql, ans.toArray());
	}

	@Override
	public List<Banner> queryData(Banner banner) throws IllegalAccessException, SQLException, InstantiationException {
		return null;
	}

	@Override
	public int update(Banner banner) throws SQLException {
		String sql = "update banner set ";
		List<Object> ans = new ArrayList<>();

		if(banner == null) return 0;

		if(banner.getImageUrl() != null) {
			sql+="image_url = ?";
			ans.add(banner.getImageUrl());
		}

		if(banner.getToUrl() != null) {
			sql+=ans.isEmpty()?"to_url = ?":",to_url = ?";
			ans.add(banner.getToUrl());
		}

		if(banner.getToRouterUrl() != null) {
			sql+=ans.isEmpty()?"to_router_url = ?":",to_router_url = ?";
			ans.add(banner.getToRouterUrl());
		}

		if(ans.isEmpty()) return 0;

		// 添加修改时间
		sql+=ans.isEmpty()?"update_time = ?":",update_time = ?";
		ans.add(new Date());

		sql+=" where id = ? ";
		ans.add(banner.getId());

		return JdbcUtil.insertOrUpdateOrDelete(sql, ans.toArray());
	}

	@Override
	public int deleteById(Object id) throws SQLException {
		String sql = "update banner set is_deleted = 1 where id = ? ";
		return JdbcUtil.insertOrUpdateOrDelete(sql,  new Object[]{id});
	}

	@Override
	public PageUtil<Banner> queryDataBypage(int currentPgae, int pageSize, Banner banner) throws IllegalAccessException, SQLException, InstantiationException {
		return null;
	}

	/**
	 * 查询所有未删除的轮播图
	 * @return
	 */
	@Override
	public List<Banner> queryList() throws SQLException, InstantiationException, IllegalAccessException {
		String sql = "select * from banner where is_deleted = 0 order by sort asc  ";

		return JdbcUtil.queryData(sql, Banner.class, null);
	}

	@Override
	public Banner findOne(int id) throws SQLException, InstantiationException, IllegalAccessException {
		String sql = "select * from banner where id = ? ";

		List<Banner> banners = JdbcUtil.queryData(sql, Banner.class, new Object[]{id});

		return banners.isEmpty()?null:banners.get(0);
	}
}
